package com.eyeem.recyclerviewtools.sample;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.alexvasilkov.android.commons.state.InstanceState;
import com.alexvasilkov.gestures.animation.ViewPositionAnimator.PositionUpdateListener;
import com.alexvasilkov.gestures.commons.DepthPageTransformer;
import com.alexvasilkov.gestures.commons.RecyclePagerAdapter;
import com.alexvasilkov.gestures.transition.SimpleViewsTracker;
import com.alexvasilkov.gestures.transition.ViewsCoordinator;
import com.alexvasilkov.gestures.transition.ViewsTransitionAnimator;
import com.alexvasilkov.gestures.transition.ViewsTransitionBuilder;
import com.eyeem.recyclerviewtools.LoadMoreOnScrollListener;
import com.eyeem.recyclerviewtools.OnItemClickListener;
import com.eyeem.recyclerviewtools.StaggeredLayoutManagerUtils;
import com.eyeem.recyclerviewtools.adapter.WrapAdapter;
import com.eyeem.recyclerviewtools.sample.adapter.DataAdapter;
import com.eyeem.recyclerviewtools.sample.data.Data;
import com.eyeem.recyclerviewtools.sample.gestureview.adapter.PhotoPagerAdapter;
import com.eyeem.recyclerviewtools.sample.gestureview.interface_.OnGesturePhotoListener;
import com.eyeem.recyclerviewtools.sample.gestureview.interface_.OnPhotoListener;
import com.eyeem.recyclerviewtools.sample.gestureview.utils.GestureSettingsMenu;
import com.eyeem.recyclerviewtools.util.Views;

import java.io.Serializable;


public class GestureViewActivity extends BaseActivity implements LoadMoreOnScrollListener.Listener,
        PositionUpdateListener, OnPhotoListener, OnGesturePhotoListener {
    private DataAdapter adapter;
    private WrapAdapter wrapAdapter;
    private ViewHolder views;
    private ViewsTransitionAnimator<Integer> animator;
    private LinearLayoutManager layoutManager;
    private GestureSettingsMenu settingsMenu;
    private PhotoPagerAdapter pagerAdapter;
    private ViewPager.OnPageChangeListener pagerListener;

    private static final int PAGE_SIZE = 30;
    private static final int NO_POSITION = -1;
    @InstanceState
    private int savedPagerPosition = NO_POSITION;
    @InstanceState
    private int savedGridPosition = NO_POSITION;
    @InstanceState
    private int savedGridPositionFromTop;
    @InstanceState
    private int savedPhotoCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture_view);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        //
        views = new ViewHolder(this);
        //添加菜单和返回按钮
        setSupportActionBar(views.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        views.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        // Adapter
        adapter = DataAdapter.generateRandom(this, this);
        wrapAdapter = new WrapAdapter(adapter);
        wrapAdapter.setOnItemClickListener(views.recycler, new OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position, long id, RecyclerView.ViewHolder viewHolder) {
                Intent intent = new Intent(GestureViewActivity.this, DetailActivity.class).putExtra("ItemInfo", (Serializable) adapter.getItem(position));
                int type = 0;
                View imageView = viewHolder.itemView.findViewById(R.id.photo);
                View textView = viewHolder.itemView.findViewById(R.id.text);
                //android.util.Pair[] pairs = new android.util.Pair[2];
                if (imageView != null/* && textView != null*/) {
                    type = 0;
                    //pairs[0] = android.util.Pair.create(imageView, textView);
                } else {
                    type = 1;
                    //pairs = new android.util.Pair[1];
                    //pairs[0] = android.util.Pair.create(textView, null);
                }

                if (Build.VERSION.SDK_INT >= 21 && imageView != null) {
                    //String transitionName = getString(R.string.transition_image);
                    //ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(GestureViewActivity.this, imageView, transitionName);
                    ActivityOptions transitionActivityOptions;
                    String transitionName;
                    if (type == 1) {
                        transitionName = getString(R.string.transition_detail);
                        transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(GestureViewActivity.this, textView, transitionName);
                    } else {
                        transitionName = getString(R.string.transition_image);
                        transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(GestureViewActivity.this, imageView, transitionName);
                    }
                    startActivity(intent, transitionActivityOptions.toBundle());
                } else {
                    ActivityCompat.startActivity(GestureViewActivity.this, intent, null);
                }

            }
        });
        // Layout manager
        layoutManager = new LinearLayoutManager(this);
        views.recycler.setLayoutManager(layoutManager);
        views.recycler.setAdapter(wrapAdapter);

        //NOTICE: 使用GestureView的时候，如果要addHeader,在adapter中增加一种布局，暂时不建议使用wrapAdapter.addHeader(new Header(this));(因为还有一个bug:图片展开的位置比实际多1)
        // Header
        //wrapAdapter.addHeader(new Header(this));

        // Load more scroller
        views.recycler.addOnScrollListener(new LoadMoreOnScrollListener(this));
        Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                String msg = "";
                switch (menuItem.getItemId()) {
                    case R.id.action_settings:
                        msg += "设置";
                        break;
                }

                if (!msg.equals("")) {
                    Toast.makeText(GestureViewActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        };
        views.toolbar.setOnMenuItemClickListener(onMenuItemClick);
        dismissRefresh(views.swipeRefreshLayout);
        //
        settingsMenu = new GestureSettingsMenu();
        settingsMenu.onRestoreInstanceState(savedInstanceState);
        initPager();
        initAnimator();
        if (savedPagerPosition != NO_POSITION) {
            // Photo was show in pager, we should switch to pager mode instantly
            onPositionUpdate(1f, false);
        }
    }

    private void initPager() {
        // Setting up pager views
        pagerAdapter = new PhotoPagerAdapter(views.pager, this);
        pagerAdapter.setSetupListener(settingsMenu);

        pagerListener = new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                onPhotoInPagerSelected(position);
            }
        };
        pagerAdapter.setPhotos(adapter.data);
        views.pager.setAdapter(pagerAdapter);
        views.pager.addOnPageChangeListener(pagerListener);
        views.pager.setPageTransformer(true, new DepthPageTransformer());
    }

    private void initAnimator() {
        animator = new ViewsTransitionBuilder<Integer>()
                .fromRecyclerView(views.recycler, new SimpleViewsTracker() {
                    @Override
                    public View getViewForPosition(int position) {
                        RecyclerView.ViewHolder holder = views.recycler.findViewHolderForLayoutPosition(position);
                        return holder == null ? null : DataAdapter.getImage(holder);
                    }
                })
                .intoViewPager(views.pager, new SimpleViewsTracker() {
                    @Override
                    public View getViewForPosition(int position) {
                        RecyclePagerAdapter.ViewHolder holder = pagerAdapter.getViewHolder(position);
                        return holder == null ? null : PhotoPagerAdapter.getImage(holder);
                    }
                })
                .build();
        animator.addPositionUpdateListener(this);
        animator.setReadyListener(new ViewsCoordinator.OnViewsReadyListener<Integer>() {
            @Override
            public void onViewsReady(@NonNull Integer id) {
                // Setting image drawable from 'from' view to 'to' to prevent flickering
                ImageView from = (ImageView) animator.getFromView();
                ImageView to = (ImageView) animator.getToView();
                if (to != null && to.getDrawable() == null) {
                    to.setImageDrawable(from.getDrawable());
                }
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        settingsMenu.onSaveInstanceState(outState);
        saveScreenState();
        super.onSaveInstanceState(outState);
        clearScreenState(); // We don't want to restore state if activity instance is not destroyed
    }

    private void saveScreenState() {
        clearScreenState();

        savedPhotoCount = adapter.getItemCount();

        savedPagerPosition = animator.isLeaving() || pagerAdapter.getCount() == 0
                ? NO_POSITION : views.pager.getCurrentItem();

        if (views.recycler.getChildCount() > 0) {
            View child = views.recycler.getChildAt(0);
            savedGridPosition = views.recycler.getChildAdapterPosition(child);
            savedGridPositionFromTop = child.getTop()
                    - com.alexvasilkov.android.commons.utils.Views.getMarginParams(child).topMargin
                    - views.recycler.getPaddingTop();
        }
    }

    private void clearScreenState() {
        savedPhotoCount = 0;
        savedPagerPosition = NO_POSITION;
        savedGridPosition = NO_POSITION;
        savedGridPositionFromTop = 0;
    }


    private void onPhotoInPagerSelected(int position) {
//        Data photo = pagerAdapter.getPhoto(position);
//        if (photo == null) {
//            views.pagerTitle.setText(null);
//        } else {
//            SpannableBuilder title = new SpannableBuilder(Ex6AdvancedDemoActivity.this);
//            title.append(photo.getTitle()).append("\n")
//                    .createStyle().setColorResId(R.color.text_secondary_light).apply()
//                    .append(R.string.photo_by).append(" ")
//                    .append(photo.getOwner().getUsername());
//            views.pagerTitle.setText(title.build());
//        }
    }

    @Override
    public void onPositionUpdate(float state, boolean isLeaving) {
        views.background.setVisibility(state == 0f ? View.INVISIBLE : View.VISIBLE);
        views.background.getBackground().setAlpha((int) (255 * state));

        views.toolbar.setVisibility(state == 1f ? View.INVISIBLE : View.VISIBLE);
        views.toolbar.setAlpha((float) Math.sqrt(1d - state)); // Slow down toolbar animation

        if (isLeaving && state == 0f) {
            pagerAdapter.setActivated(false);
        }
    }

    @Override
    public void onPhotoClick(int position) {
        pagerAdapter.setActivated(true);
        animator.enter(position + wrapAdapter.getHeaderCount(), true);
    }

    @Override
    public void onPhotoClick(int position, View view) {

    }

    @Override
    public void onGesturePhotoClick(int position) {
        onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_space, menu);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (!animator.isLeaving()) {
            animator.exit(true);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onLoadMore(RecyclerView recyclerView) {
        wrapAdapter.showLoadMore();
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < 5; i++) {
                    adapter.data.add(Data.newRandom(GestureViewActivity.this));
                }

                if (views.recycler.getLayoutManager() instanceof StaggeredGridLayoutManager) {
                    StaggeredLayoutManagerUtils.onItemChanged(views.recycler, 0);
                }
                adapter.notifyDataSetChanged();
                wrapAdapter.hideLoadMore();

            }
        }, 1000);
    }


    private static class ViewHolder {
        final Toolbar toolbar;
        final ViewPager pager;
        final View background;
        final RecyclerView recycler;
        final SwipeRefreshLayout swipeRefreshLayout;

        ViewHolder(Activity activity) {
            toolbar = Views.find(activity, R.id.toolbar);
            pager = Views.find(activity, R.id.transition_pager);
            background = Views.find(activity, R.id.transition_full_background);
            recycler = Views.find(activity, R.id.recycler);
            swipeRefreshLayout = Views.find(activity, R.id.swipe_container);
        }
    }
}
